package com.mingtu.guards.utils;

import android.os.Environment;

import com.amap.api.maps.model.TileOverlayOptions;
import com.amap.api.maps.model.UrlTileProvider;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.utils.SPTools;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

import static com.mingtu.guards.utils.MyConstant.MAP_INDEX_TILE;
import static com.mingtu.guards.utils.MyConstant.MAX_ZOOM;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2021-9-16 11:14:43
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class TileUtils {
    private static final String TileUrlHost = "https://static.mingtukeji.com/jiaozuo/tiles/";
    public static final String File_Directory = BaseApplication.getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/mapImg";

    public static TileOverlayOptions getTileOverlayOptions() {
        TileOverlayOptions tileOverlayOptions = new TileOverlayOptions();
        tileOverlayOptions.memoryCacheEnabled(true);
        tileOverlayOptions.diskCacheEnabled(true);
        tileOverlayOptions.visible(true);
        tileOverlayOptions.zIndex(MAP_INDEX_TILE);
        tileOverlayOptions.tileProvider(new MyUrlTileProvider(256, 256));
        return tileOverlayOptions;
    }

    private static class MyUrlTileProvider extends UrlTileProvider {

        public MyUrlTileProvider(int i, int i1) {
            super(i, i1);
            OkDownload.getInstance().getThreadPool().setCorePoolSize(2);
        }

        @Override
        public URL getTileUrl(int x, int y, int zoom) {
//            MyLogUtil.e("zoom", "zoom==============" +zoom);
            try {
                if (!MyConstant.isShowTile) {
                    return null;
                }
                if (zoom > MAX_ZOOM) {
                    return null;
                }
                String XYZOOM = SPStaticUtils.getString(MySPTools.XYZOOM);
                if (!XYZOOM.contains(zoom + "_" + x + "_" + y)) {
                    return null;
                }
                String tag = zoom + "_" + x + "_" + y + ".png";
                String imgUrl = TileUrlHost + zoom + "/" + x + "/" + y + ".png";
                File file = new File(File_Directory + "/", zoom + "/" + x + "_" + y + ".png");
                boolean netWorkState = SPStaticUtils.getBoolean(SPTools.netWorkState);

                if (netWorkState) {
//                    try {
                    if (!FileUtils.isFileExists(file)) {
//                            if (isImagesTrue(imgUrl) == 200) {
                        GetRequest<File> request = OkGo.<File>get(imgUrl);
                        if (OkDownload.getInstance().getTask(tag) == null) {
                            //未在任务队列
                            //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一
                            OkDownload.request(tag, request)//
                                    .folder(File_Directory + "/" + zoom) //单独指定当前下载任务的文件夹目录,文件名字默认为下载的文件名
                                    .save()//
                                    .start();
                        } else {
                            //已经在任务队列,如果未完成
                            Progress progress = OkDownload.getInstance().getTask(tag).progress;
                            int status = progress.status;
                            if (status != Progress.FINISH) {
                                OkDownload.request(tag, request)//
                                        .folder(File_Directory + "/" + zoom)
                                        .save()//
                                        .start();
                            }
                        }
//                            }
                    } else {
                        imgUrl = "file://" + file.getAbsolutePath();
                        if (OkDownload.getInstance().getTask(tag) != null) {
                            Progress progress = OkDownload.getInstance().getTask(tag).progress;
                            int status = progress.status;
                            if (status == Progress.FINISH) {
                                OkDownload.getInstance().removeTask(tag);
                            }
                        }

                    }

//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }

                } else {
                    if (FileUtils.isFileExists(file)) {
                        imgUrl = "file://" + file.getAbsolutePath();
                        if (OkDownload.getInstance().getTask(tag) != null) {
                            Progress progress = OkDownload.getInstance().getTask(tag).progress;
                            int status = progress.status;
                            if (status == Progress.FINISH) {
                                OkDownload.getInstance().removeTask(tag);
                            }
                        }
                    }
                }


                URL url = null;
                try {
                    url = new URL(imgUrl);
                } catch (MalformedURLException e) {

                    throw new AssertionError(e);
                }
                return url;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
